package com.chazz.webSoket;

import com.chazz.dao.impl.UserDaoImpl;
import com.chazz.entity.User;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint("/chat")
public class WebSoket {
    //存Session
    private static Map<String,Session> saveSession=new HashMap();
    //存用户、SessionId,userEmail
    private static Map<String,String> saveSE=new HashMap<>();
    //存用户 userEmail,SessionId
    private static Map<String,String> saveES=new HashMap<>();
    UserDaoImpl udi=new UserDaoImpl();
    User user=null;
    User sentToWhoUser=null;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("连接成功");
        //加入连接，放入Map中
        saveSession.put(session.getId(),session);
        session.getBasicRemote().sendText("聊天开始");
    }

    @OnClose
    public void onclose(Session session){
        System.out.println("退出");
        String delE=saveSE.get(session.getId());
        String delSE=saveES.get(delE);
        saveSE.remove(delSE);
        saveES.remove(delE);
        saveSession.remove(session.getId());


    }

    @OnMessage
    public void onsend(Session session,String msg){
        try {
            //1、用户发来的消息处理（分割符前为用户邮箱，后为消息）
            String[] getMsg=msg.split("`~``~");
            String userEmail=getMsg[0];
            String sendMsg=getMsg[1];
            String sendToWhoIdS=null;
            String sendToWhoEmail = null;
            String sendToWhoName=null;
            int sendToWhoId=-1;


                boolean flag = false;
                for (String key : saveES.keySet()) {
                    if (key.equals(userEmail)) {
                        flag = true;
                    }
                }
                //集合中没有，用户、客服第一次发消息
                if (flag == false) {
                    //绑定SessionID和用户邮箱
                    saveSE.put(session.getId(), userEmail);
                    saveES.put(userEmail,session.getId());
                    //连接简历客服会发一条绑定消息，不需要推送消息
                    if(userEmail.equals("2312111756@qq.com")){
                        return;
                    }
                    //发送标识是新用户
                }

            if(userEmail.equals("2312111756@qq.com")){
                sendToWhoIdS=getMsg[2];
                sendToWhoId=Integer.parseInt(sendToWhoIdS);
                sentToWhoUser=udi.findUserById(sendToWhoId);
                sendToWhoEmail=sentToWhoUser.getEmail();
                sendToWhoName=sentToWhoUser.getUsername();
            }

                //用户发的发消息
            if(userEmail.equals("2312111756@qq.com")==false) {
                        String serverSesionId = saveES.get("2312111756@qq.com");
                        Session serverSession = saveSession.get(serverSesionId);
                        user=udi.findUserByEmail(userEmail);
                        String userName=user.getUsername();
                        int userId=user.getId();
                        //发送消息
                        session.getBasicRemote().sendText("您:" + sendMsg);
                        serverSession.getBasicRemote().sendText("用户：" + sendMsg+"`~``~"+userId+"`~``~"+userName);
             //这条消息是客服发的
            }else{
                session.getBasicRemote().sendText("你:" + sendMsg+"`~``~"+sendToWhoId+"`~``~"+sendToWhoName);
                for (String key : saveSession.keySet()) {
                    if(key.equals(saveES.get(sendToWhoEmail))) {
                        Session session1 = saveSession.get(key);
                        session1.getBasicRemote().sendText("客服:" + sendMsg);
                    }
                }
            }

        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }

}
